package com.mcc.myapplication

fun getNum(): Number {
    return 100F
}

/**
 * is 与 !is 操作符
 */
fun isDemo() {
    val obj = "hello"
    if (obj is String) {
        println("string length:${obj.length}")
    }
    val value = 1
    if (value is Int) {
        println("$value is Int")
    }
    val num = getNum()
    if (num !is Int) {
        println("$num not is Int")
    }
}

/**
 *  智能转换
 */
fun transferDemo(x: Any) {
    if (x is String) {

        println("this param is string, and length:${x.length}") // x 自动转换为字符串
    }
}

fun transferDemo2(x: Any) {
    if (x !is String) return
    // 如果反向检测导致返回那么该转换是安全的
    println("this param is string, and length:${x.length}")
}

fun transferDemo3(x: Any) {
    // `||` 右侧的 x 自动转换为 String
    if (x !is String || x.length == 0) return

    // `&&` 右侧的 x 自动转换为 String
    if (x is String && x.length > 0) {
        println("this param is string, and length:${x.length}")
    }
}

fun transferDemo4(x: Any) {
    when (x) {
        is Int -> print(x + 1)
        is String -> print(x.length + 1)
        is IntArray -> print(x.sum())
    }
}

fun transferDemo5(x: Any) {
    // “不安全的”转换操作符
    val y: String? = x as String?
    if (y != null) {
        println("this param is string, and length:${x.length}")
    }
}

fun transferDemo6(x: Any) {
    // “安全的”（可空）转换操作符
    val y: String? = x as? String
    if (y != null) {
        println("this param is string, and length:${x.length}")
    }
}

fun main() {
    isDemo()
    transferDemo("world")
    transferDemo2("gogogo")
    transferDemo3("pythonX")
    transferDemo4(intArrayOf(1, 2, 3, 4, 5))
    transferDemo4(arrayOf(1, 2, 3, 4, 5, 6))
//    transferDemo5(111)
    transferDemo6(111)
}